# figure_4.R

rm(list = ls())
setwd("/Users/John/Dropbox/")

# --- Load Required Packages ---
library(readr)
library(interflex)
library(tidyverse)

# --- Load Data  ---
df <- read_csv("JOP_Replication_Materials/data/processed/final_dataset.csv")

# --- Prepare Data ---
intflex <- df %>%
  dplyr::select(isic, year, strategic, isic_year, median_share,  
                med_hhi_isic2, med_soe_isic2) %>%
  mutate(Strategic = strategic)

intflex <- as.data.frame(intflex)

# --- Run Interflex Model ---
int.p <- interflex(
  estimator = "binning",
  Y = "isic_year",
  D = "Strategic",
  X = "median_share",
  Z = c("med_hhi_isic2", "med_soe_isic2"),
  data = intflex,
  vcov.type = "cluster",
  cl = "isic",
  na.rm = TRUE,
  main = "Marginal Effect of Strategic Status on Tech Absorption",
  Ylabel = "Tech Abs. Policies",
  Xlabel = "Median Processing Share",
  method = "poisson",
  cex.main = 1,
  ncols = 1,
  theme.bw = TRUE,
  nbins = 3,
  bin.labs = FALSE
)

# --- Print figure ---
plot(int.p$figure + theme(plot.margin = margin(10, 10, 10, 10)))

int.p$tests$p.wald

# Manually save as "Dropbox/JOP_Replication_Materials/output/figures/figure_4.pdf" to ensure best figure dimensions

# -- Print Bin Estimates for Log File ---

print(int.p$est.bin)
